import { Controller, Get, Post, Req, Res } from '@nestjs/common'
import { WorkbenthService } from './workbenth.service'
import { Request, Response } from 'express'
import { OrderService } from '../order/order.service'

interface HeaderData {
  // 实收金额
  actualAmount: number
  // 实付金额
  actualPayAmount: number
  // 销售订单数量
  salesOrderCount: number
  // 人均消费金额
  perCapitaConsumption: number
  // 新客
  newCustomer: number
  // 老客
  oldCustomer: number
}

@Controller('workbenth')
export class WorkbenthController {
  constructor(
    private readonly workbenthService: WorkbenthService,
    private readonly OrderService: OrderService,
  ) {}

  @Post('headerData')
  getHeaderData(@Req() req: Request, @Res() res: Response) {
    const data: HeaderData = {} as HeaderData
    res.send(data)
  }

  @Get('SearchOptions')
  async getSearchOptions(@Req() req: Request, @Res() res: Response) {
    const {
      brand = '',
      partition = '',
      shop = '',
      source = '',
      status = '',
      timeRange = '7',
    } = req.query
    let data = await this.OrderService.getorderlist()

    const date = this.workbenthService.generateDays(String(timeRange))
    // 营业趋势分布图
    const BusinessTrend = {
      date: date,
      data: date.map((e) => this.workbenthService.getTotalPriceByDate(e, data)),
    }

    const values = this.workbenthService.calculatePercentageByDealTimeAndSource(
      Number(timeRange),
      data,
    )

    const OrderSources = Object.entries(values).map((entry) => {
      const [key, value] = entry
      return { value: parseFloat(value.toFixed(2)), name: key }
    })

    const prices =
      this.workbenthService.calculatePricePercentageByDealTimeAndSource(
        Number(timeRange),
        data,
      )

    const price = Object.entries(prices).map((entry) => {
      const [key, value] = entry
      return { value: parseFloat(value.toFixed(2)), name: key }
    })

    const result = this.workbenthService.calculateOrderStatistics(
      String(timeRange),
      data,
    )
    result['validOrderPercent'] = Number((result.PerCapitaConsumptionAmount / result.SalesOrderNumber) * 100).toFixed(2);

    const SelectOptions = this.workbenthService.getSearchOptions()
    res.send({
      result,
      SelectOptions,
      BusinessTrend,
      OrderSources,
      price,
    })
  }
}
